package net.jsoft.platform.security.web.user;

import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;

import net.jsoft.platform.core.web.BaseController;
import net.jsoft.platform.security.entity.user.SysRole;
import net.jsoft.platform.security.entity.user.SysUser;
import net.jsoft.platform.security.repository.UserRepository;
import net.jsoft.platform.security.util.MD5Util;
import net.jsoft.pms.entity.dept.Dept;

@Controller
@RequestMapping("/user")
public class UserController extends BaseController
{

    @Autowired
    private UserRepository repository;

    @RequestMapping("/list")
    @PreAuthorize("hasAuthority('ROLE_ADMIN')")
    public String list()
    {
        return "/platform/security/user/list";

    }

    @RequestMapping("/listData")
    @ResponseBody
    @PreAuthorize("hasAuthority('ROLE_ADMIN')")
    public JSONObject listData(int pageSize, int pageNumber)
    {
        JSONObject json = new JSONObject();
        PageRequest request = new PageRequest(pageNumber - 1, pageSize, null);
        Page<SysUser> list = repository.findAll(request);
        json.put("rows", list.getContent()); //这里的 rows 和total 的key 是固定的 
        json.put("total", list.getTotalElements());
        return json;
    }

    @RequestMapping("/add")
    @PreAuthorize("hasAuthority('ROLE_ADMIN')")
    public String add()
    {
        return "/platform/security/user/add";

    }

    @RequestMapping("/addSave")
    @ResponseBody
    @PreAuthorize("hasAuthority('ROLE_ADMIN')")
    public String addSave(SysUser user, long sszb)
    {
        String returnMsg = "ok";
        //        Dept dept = repository.findDept(Long.parseLong(sszb));
        Dept dept = repository.findDept(sszb);
        SysUser u = repository.findByName(user.getName());
        if (u != null)
        {
            returnMsg = "该用户名已存在";
        }
        else
        {
            user.setPassword(MD5Util.getMd5(user.getName() + user.getPassword()));
            user.setDept(dept);
            repository.save(user);
        }

        return returnMsg;

    }

    @RequestMapping("/edit")
    @PreAuthorize("hasAuthority('ROLE_ADMIN')")
    public String edit(SysUser user, Model model)
    {
        user = repository.findOne(user.getId());
        model.addAttribute("user", user);
        return "/platform/security/user/edit";

    }

    @RequestMapping("/editSave")
    @ResponseBody
    @PreAuthorize("hasAuthority('ROLE_ADMIN')")
    public String editSave(SysUser user, long sszb)
    {
        String returnMsg = "ok";
        SysUser u = repository.findOne(user.getId());
        u.setEmail(user.getEmail());
        u.setFullName(user.getFullName());
        u.setPhone(user.getPhone());
        if (StringUtils.isNotEmpty(user.getPassword()))
        {
            u.setPassword(MD5Util.getMd5(user.getName() + user.getPassword()));
        }
        Dept dept = repository.findDept(sszb);
        u.setDept(dept);
        repository.save(u);
        return returnMsg;

    }

    @RequestMapping("/delSave")
    @ResponseBody
    @PreAuthorize("hasAuthority('ROLE_ADMIN')")
    public String delSave(SysUser user)
    {
        String returnMsg = "ok";
        repository.delete(user.getId());
        return returnMsg;

    }

    @RequestMapping("/role")
    @PreAuthorize("hasAuthority('ROLE_ADMIN')")
    public String role(SysUser user, Model model)
    {
        user = repository.findOne(user.getId());
        model.addAttribute("user", user);
        List<SysRole> roles = repository.findAllRole();
        Map<String, SysRole> roleMap = new HashMap<String, SysRole>();
        for (SysRole r : roles)
        {
            roleMap.put(r.getId() + "", r);
        }

        Set<SysRole> s = user.getSysRoles();
        for (SysRole r : s)
        {
            SysRole temp = roleMap.get(r.getId() + "");
            temp.setChecked("1");
            roleMap.put(r.getId() + "", temp);
        }
        model.addAttribute("roles", roleMap.values().toArray());
        return "/platform/security/user/role";
    }

    @RequestMapping("/roleSave")
    @ResponseBody
    @PreAuthorize("hasAuthority('ROLE_ADMIN')")
    public String roleSave(String ids, SysUser user)
    {
        String returnMsg = "ok";
        String[] idsS = ids.split(",");
        Set<SysRole> roles = new HashSet<SysRole>();
        SysRole r = null;
        for (String s : idsS)
        {
            r = new SysRole();
            r.setId(Long.parseLong(s));
            roles.add(r);
        }
        user = repository.findOne(user.getId());
        user.setSysRoles(roles);
        repository.save(user);

        return returnMsg;

    }

    @RequestMapping("/getUsers")
    @ResponseBody
    public Map<String, Object> getUsers(long sszb)
    {
        Map<String, Object> map = new HashMap<String, Object>();
        Dept dept = repository.findDept(sszb);
        List<SysUser> list = repository.findByDept(dept);
        map.put("list", list);
        return map;

    }

}
